angular.module('baisonDirectives',[])
.directive('bsPager',function() {
        return {
            templateUrl: './html/directive/directive_page.html',
            replace: false,
            restrict: 'E',
            scope: false,
            controller:['$scope', '$element', function ($scope, $element) {
                $scope.page.pageSize = 10;//每页记录数
                $scope.page.count= 0;     //总共记录数
                $scope.page.totalPage=[]; //页码数组
                $scope.page.p = 1;         //当前页码
                $scope.page.num = 1;      //总共有多少页
                $scope.page.next = function () {
                    if ($scope.page.p < $scope.page.num) {
                        $scope.page.p++;
                        $scope.page.page_go($scope.page.p);
                    }
                };
                $scope.page.prev = function () {
                    if ($scope.page.p > 1) {
                        $scope.page.p--;
                        $scope.page.page_go($scope.page.p);
                    }
                };

                //重新计算页码数
                $scope.page.recount_page = function(){
                    $scope.page.totalPage = [];
                    if ($scope.page.num > 5) {
                        if ($scope.page.p - 2 <= 1) {
                            for (var i = 1; i <= 5; i++) {
                                $scope.page.totalPage.push(i);
                            }
                            $scope.page.totalPage.push('...');
                        }
                        if ($scope.page.p + 2 >= $scope.page.num) {
                            $scope.page.totalPage.push('...');
                            for (var i = $scope.page.p - 4; i <= $scope.page.num; i++) {
                                $scope.page.totalPage.push(i);
                            }
                        }
                        if ($scope.page.p - 2 > 1 && $scope.page.p + 2 < $scope.page.num) {
                            $scope.page.totalPage.push('...');
                            for (var i = $scope.page.p - 2; i <= $scope.page.p + 2; i++) {
                                $scope.page.totalPage.push(i);
                            }
                            $scope.page.totalPage.push('...');
                        }
                    } else {
                        for (var i = 1; i <= $scope.page.num; i++) {
                            $scope.page.totalPage.push(i);
                        }
                    }
                };
            }],
            link: function (scope, iElement, iAttrs) {
                scope.page.page_go_init(); 
            }
        }
    })
.directive('bsCatalogue',function() {
        return {
            templateUrl: './html/directive/directive_catalogue.html',
            replace: false,
            restrict: 'E',
            scope: false,
            controller:['$scope', '$element', function ($scope, $element) {
                // console.log("bsCatalogue controller: function");
                
                // 显示目录的数据 data_list 数据格式
                // [{name:myName,..., data:[{name:myName, isChecked:boolValue, ...}, ...]},
                //  {name:myName,..., data:[{name:myName, isChecked:boolValue, ...}, ...]},
                //  ...]
                $scope.catalogue.data_list = [];
                $scope.catalogue.check_c1_index = 0;//第一级目录选择的下标
                //点击第一层目录项
                $scope.catalogue.lowLevel = 'lowLevel';
                $scope.catalogue.click_c1 = function(index){
                    if($scope.catalogue.lowLevel == index){
                      $scope.catalogue.lowLevel = 'lowLevel';  
                    }else{
                      $scope.catalogue.lowLevel = index;  
                    };
                    $scope.catalogue.check_c1_index = index;
                };

                //点击第二层目录项
                $scope.catalogue.click_c2 = function(index){
                    if($scope.catalogue.data_list[$scope.catalogue.check_c1_index].data[index].isChecked){
                        $scope.catalogue.data_list[$scope.catalogue.check_c1_index].data[index].isChecked = false;
                    }else{
                        $scope.catalogue.data_list[$scope.catalogue.check_c1_index].data[index].isChecked = true;
                    } 
                    
                    //第二层目录选择状态变化 事件通知 传入参数发生变化的节点位置(第一级位置, 第二级位置) 
                    $scope.catalogue.data_check_change($scope.catalogue.check_c1_index, index);
                };
            }],
            link: function (scope, iElement, iAttrs) {
                scope.catalogue.catalogue_init();  
            }
        }
    })
.directive('bsGoodsCatalogue',function() {
        return {
            templateUrl: './html/directive/directive_goods_catalogue.html',
            replace: false,
            restrict: 'E',
            scope: false,
            controller:['$scope', '$element', function ($scope, $element) {
                // console.log("bsGoodsCatalogue controller: function");

                $scope.catalogue = {}; 
                $scope.catalogue.catalogue_init = function () {
                    //初始化数据
                    $scope.catalogue.data_list = [];//目录数据
                    $scope.goodsCatalogue.goods_list = [];//商品数据
                    $scope.goodsCatalogue.categoryDic = {};//大类数据(key-value:code-name)
                    $scope.goodsCatalogue.sortDic = {};//品牌数据(key-value:code-name)
                    $scope.goodsCatalogue.CunHuoPeiHuo.get_category_list().then(function (response) {//大类数据
                        var dataCategory = {"name": "大类", "searchName": "CategoryCode", "data": []};
                        for (var i = 0; i < response.length; ++i) {
                            var category = response[i];
                            category.name = category.category_name;
                            category.searchValue = category.category_code;
                            dataCategory.data.push(category);
                            $scope.goodsCatalogue.categoryDic[category.category_code] = category.category_name;
                        }
                        $scope.catalogue.data_list.push(dataCategory);
                    });
                    $scope.goodsCatalogue.CunHuoPeiHuo.get_sort_list().then(function (response) {//品牌数据
                        var dataSort = {"name": "品牌", "searchName": "SortCode", "data": []};
                        for (var i = 0; i < response.length; ++i) {
                            var sort = response[i];
                            sort.name = sort.sort_name;
                            sort.searchValue = sort.sort_code;
                            dataSort.data.push(sort);
                            $scope.goodsCatalogue.sortDic[sort.sort_code] = sort.sort_name;
                        }
                        $scope.catalogue.data_list.push(dataSort);
                    });

                    //选择状态变化
                    $scope.catalogue.data_check_change = function (index1, index2) {
                        var selectedConditonsStr = "";//查询的字符串
                        for (var i = 0; i < $scope.catalogue.data_list.length; ++i) {
                            var data1 = $scope.catalogue.data_list[i];//第一层
                            var conditions = {"name": data1.searchName, "value": []};//保存选择的数据
                            for (var j = 0; j < data1.data.length; ++j) {//第二层
                                var data2 = data1.data[j];
                                if (data2.isChecked) {
                                    conditions.value.push(data2.searchValue);
                                }
                            }

                            if (conditions.value.length > 0) {
                                if (selectedConditonsStr != "") {
                                    selectedConditonsStr += " and ";
                                }

                                selectedConditonsStr += conditions.name + " in ('" + conditions.value[0] + "'";
                                for (var j = 1; j < conditions.value.length; ++j) {
                                    selectedConditonsStr += ",'" + conditions.value[j] + "'";
                                }
                                selectedConditonsStr += ")";
                            }
                        }

                        if (selectedConditonsStr != "") {//查询字符串不为空
                            $scope.goodsCatalogue.GoodsBase.get_goods_by_condition(selectedConditonsStr).then(function (response) {
                                $scope.goodsCatalogue.goods_list = response;
                            });
                        } else {//查询字符串为空 数字也置空
                            $scope.goodsCatalogue.goods_list = [];
                        }
                    }; 
                };
            }],
            link: function (scope, iElement, iAttrs) {

                scope.goodsCatalogue.goods_catalogue_init();
            }
        }
    })
    /**
     * 指定商品范围级别的
     *
     */
    .directive('bsPdrwdCatalogue',function() {
        return {
            templateUrl: './html/directive/directive_pdrwd_catalogue.html',
            replace: false,
            restrict: 'E',
            scope: false,
            controller:['$scope', '$element','CunHuoPeiHuo','CunHuoPanDian','ngDialog',function ($scope, $element,CunHuoPeiHuo,CunHuoPanDian,ngDialog) {
                $scope.catalogue = {};
                $scope.catalogue_init = function () {
                    //初始化数据:存放左边商品分类信息
                    $scope.Catalogue = [];
                    //存放选中的指定商品范围数据
                    $scope.pdrwd_catelogue = {};
                    $scope.pdrwd_catelogue.left_catelogue = [];
                    $scope.pdrwd_catelogue.right_catelogue = [];
                    CunHuoPeiHuo.get_category_list().then(function (response) {//大类数据
                        var dataCategory = {'code':'001','name': '大类','data': []};
                        for (var i = 0; i < response.length; ++i) {
                            var category = response[i];
                            dataCategory.data.push({
                                '_code':category.category_code,
                                '_name':category.category_name,
                                '_check':false
                            });
                        }
                        $scope.Catalogue.push(dataCategory);
                    });
                    CunHuoPeiHuo.get_sort_list().then(function (response) {//品牌数据
                        var dataSort = {'code':'002','name':'品牌','data': []};
                        for (var i = 0; i < response.length; ++i) {
                            var sort = response[i];
                            dataSort.data.push({
                                '_code':sort.sort_code,
                                '_name':sort.sort_name,
                                '_check':false
                            });
                        }
                        $scope.Catalogue.push(dataSort);
                    });
                };
                $scope.catalogue_init();
                //选中左边的类别，获取具体分类
                $scope.choose_cata = function(goods){
                    $scope._goods = goods;
                };
                /**
                 * //获取具体分类:index:表示左边的类别，data:具体的分类,例子
                 * @param index
                 * @param data
                 * index:{code:001,name:大类,data:[{_code:000,_name:未定义},{_code:002,_name:帽子},......]}
                 * data:{_code:000,_name:未定义,_check:false,code:001,name:大类}
                 * $scope.pdrwd_catelogue.right_catelogue：[{_code:000,_name:未定义,_check:false,code:001,name:大类},...]
                 */
                $scope.choose_catelogue = function(index,data){
                    //给data增加一个左边分类的值
                    var flag2 = false;
                    if($scope.pdrwd_catelogue.right_catelogue.length > 0){
                        $.each($scope.pdrwd_catelogue.right_catelogue,function(_i,_n){
                            if(_n._code == data._code){
                                //判断左边的分类是否相同
                                if(_n.code == index.code){
                                    flag2 = false;
                                    _n._check = !(_n._check);
                                    return false;
                                }else{
                                    flag2 = true;
                                }
                            }else{
                                flag2 = true;
                            }
                        });
                        if(flag2){
                            data._check = !(data._check);
                            data.code = index.code;
                            data.name = index.name;
                            $scope.pdrwd_catelogue.right_catelogue.push(data);
                        }
                    }else{
                        data._check = !(data._check);
                        data.code = index.code;
                        data.name = index.name;
                        $scope.pdrwd_catelogue.right_catelogue.push(data);
                    }
                    //将数组进行组合成：一个大类对应下面多个品牌
                    //console.log(3434,$scope.pdrwd_catelogue.right_catelogue);
                    var _array = [];
                    $scope.pdrwd_array = [];
                    $.each($scope.pdrwd_catelogue.right_catelogue,function(m,l){
                        if(!_array.some(function(x){
                                return x.code == l.code
                            })){
                            //选中的添加
                            if(l._check == true){
                                _array.push({
                                    'code':l.code,
                                    'name':l.name
                                });
                            }
                        }
                    });
                    for(var _l=0;_l<_array.length;_l++){
                        var pdrwdsp = {};
                        pdrwdsp.key = _array[_l].name;
                        pdrwdsp.value = [];
                        for(var _m=0;_m<$scope.pdrwd_catelogue.right_catelogue.length;_m++){
                            if(_array[_l].code == $scope.pdrwd_catelogue.right_catelogue[_m].code && $scope.pdrwd_catelogue.right_catelogue[_m]._check == true){
                                pdrwdsp.value.push($scope.pdrwd_catelogue.right_catelogue[_m]);
                            }
                        }
                        $scope.pdrwd_array.push(pdrwdsp);
                    }
                    //定义一个数组存放选中的字符串
                    $scope.str = [];
                    for(var i = 0;i<$scope.pdrwd_array.length;i++){
                        var str1 = '';
                        str1 = $scope.pdrwd_array[i].key +":";
                        for(var j=0;j<$scope.pdrwd_array[i].value.length;j++){
                            str1 += ($scope.pdrwd_array[i].value)[j]._name+"/";
                        }
                        str1 = str1.substring(0,str1.length-1);
                        $scope.str.push(str1);
                    }

                };
            }]
        }
    })
   /**快捷键指令
     * @example:<button  bs-shortcut="ctrl+a" type="button" ng-click="goto_index(); ">去首页</button>
    * */
    .directive('bsShortcut',function() {
        return {
            restrict: 'A',
            scope: false,
            controller:['$scope', '$element','$route','$attrs','shortCutAction', function ($scope, $element,$route,$attrs,shortCutAction) {
                shortCutAction.handler($route.current.$$route.originalPath, $attrs.bsShortcut, function () {
                    $element[0].click();
                });
            }]
        }
    })
    /**移动设备触摸事件,解决平板上点击延迟的问题,兼容pc端click事件
     * 使用方法: 用bs-touchstart替换原来的ng-click
     * @example:<a class="keys"  bs-touchstart="btn_number(7);">
     * */
    .directive("bsTouchstart", function () {
        return {
            controller: ["$scope", "$element", function ($scope, $element) {
                $element.bind("touchstart", onTouchStart);
                $element.bind("click", onClick);
                function onTouchStart(event) {
                    $element.unbind("click");
                    var method = $element.attr("bs-touchstart");
                    $scope.$apply(method);
                }
                function onClick(event) {
                    $element.unbind("touchstart");
                    var method = $element.attr("bs-touchstart");
                    $scope.$apply(method);
                }
            }]
        }
    })
    /**
     * 打开小键盘
     * @example 在页面加上<bs-num-keyboard></bs-num-keyboard>
     *          在需要打开小键盘的时候调用$scope.open_keyboard('goods.num');//参数根据实际情况传
     *          需要关闭时调用$scope.close_keyboard();
     * */
    .directive('bsNumKeyboard',function() {
        return {
            templateUrl: './html/directive/dialog_num_keyboard.html',
            replace:false,
            restrict: 'EA',
            scope: false,
            controller:['$scope', '$element','$route','$attrs','$parse', function ($scope, $element,$route,$attrs,$parse) {
                var input_model_str;
                var input_model_value;
                var input_model;
                var handle = function (e) {
                	//baison_app.api.alert({msg:e,title:'ee'});
                    if(e.hasOwnProperty('path') && e.path[0].attributes.hasOwnProperty('ng-model')) {
                        input_model_str = e.path[0].attributes['ng-model'].value;  //当前获取焦点的ng-model值
                    }
                    // console.log(input_model_str);
                };
                /**
                 * 打开小键盘
                 * @example <input ng-model="list.record_code">
                 *     $scope.open_keyboard('list.record_code');
                 * @param input|string 可选参数; 传ng-model属性的值;决定打开小键盘时默认输入到哪里;
                 * */
                $scope.open_keyboard = function (input) {
                    document.addEventListener('focus', handle, true);
                    $scope.show_keyboard=true;
                    if(input!=undefined) {
                        input_model_str = input;
                    }
                    $scope.btn_number = function(n){
                        if(input_model_str==undefined||input_model_str==''){
                            return
                        }
                        //baison_app.api.alert({msg:input_model_str});
                        input_model_value = $scope.$eval(input_model_str);
                        // console.log(input_model_value);
                        if(input_model_value==undefined) {
                            input_model_value = '';
                        }
                        if(typeof input_model_value != 'string'){
                        	input_model_value = input_model_value.toString();
                        }
                        //baison_app.api.alert({msg:typeof input_model_value});
                        // console.log(input_model_value);
                        input_model=$parse(input_model_str);
                        if(n=='backspace'){
                            input_model_value=input_model_value.substr(0,input_model_value.length-1);
                        }else{
                            input_model_value+=n+'';
                        }
                        input_model.assign($scope, input_model_value); //将改变后的值赋值
                    };
                };
                
                /**关闭小键盘
                 * */
                $scope.close_keyboard = function () {
                    input_model_str = '';
                    $scope.show_keyboard=false;
                    document.removeEventListener('focus', handle, true);//移除监听
                    if(!$scope.$$phase) {
                        $scope.$apply();
                    }
                };
                /**设置ng-model
                 * @example goods_data[3][2].num
                 * */
                $scope.set_input_model = function (model) {
                    input_model_str = model;
                }
            }]
        }
    })
    /**
     * 封装一个搜索商品的指令
     * 参数：input_keywords
     */
    .directive('bsShortcut',function() {
        return {
            restrict: 'E',
            scope: false,
            templateUrl: '<div class="search search_sm"> <input class="search_input" id="input_sku" type="tel" ng-model="input_keywords" /> <button class="search_btn" ng-click="search_goods(input_keywords);">{{language.ACT_SEARCH}}</button> </div>',
            controller:['$scope', '$element','$route','$attrs','GoodsBase', function ($scope, $element,$route,$attrs,GoodsBase) {
                //编辑数量:window_edit_id、选择商品:window_id
                var window_edit_id = 0;
                var window_id = 0;
                /**
                 * 根据关键词搜索
                 * @param input_keywords
                 */
                var search_sku = function(input_keywords){
                    //根据要货类型搜索相关商品
                    GoodsBase.get_sku_by_code(input_keywords).then(function (ret) {
                        if (Object.keys(ret).length == 0) {
                            baison_app.api.toast({
                                buttons: [$rootScope.language.COMMON_CONFIRM_BUTTON],
                                msg: $rootScope.language.TIPS_CUNHUO_SEARCH_GOODS
                            });
                            return false;
                        }
                        //只有一条数据时，直接添加
                        if (Object.keys(ret).length == 1) {
                            if ($rootScope.configData.choseGoodsType == 1) {
                                //get_goods_by_code_local(ret[0].GoodsCode);
                            } else {
                                $scope.sku = ret[0];
                                $scope.sku.num;
                                window_edit_id = ngDialog.open({closeByDocument: false,
                                    trapFocus: false,
                                    template: './html/component/component_edit_num.html',
                                    disableAnimation: true,
                                    scope: $scope,
                                });
                            }
                        } else {
                            $scope.goods_select_data_choose = 0;
                            $scope.goods_select_data = ret;
                            window_id = ngDialog.open({closeByDocument: false,
                                trapFocus: false,
                                template: './html/component/component_goods_select.html',
                                disableAnimation: true,
                                scope: $scope,
                            });
                        }
                    });
                };
                /**
                 * 不输入商品时选择弹出大框
                 */
                $scope.select_goods = function () {
                    //商品选择大弹窗
                    window_id = ngDialog.open({
                        className: 'ngdialog-theme-plain',
                        closeByDocument: false,
                        trapFocus: false,
                        disableAnimation: true,
                        scope: $scope,
                        template: './html/component/component_goods_select_senior.html',
                        controller: [function () {
                            //标题
                            $scope.title = "商品选择";
                        }]
                    });
                };
                /**
                 * 搜索商品
                 * @param input_keywords
                 * @returns {boolean}
                 */
                $scope.search_goods = function(input_keywords){
                    var key = new String(input_keywords);
                    if ('' == input_keywords || Object.keys(key).length < 3) {
                        //商品大框
                        $scope.select_goods();
                        return false;
                    }
                    search_sku(input_keywords);
                };
                /**
                 * 当搜索出多条sku时，需要选择商品
                 * @param sku
                 */
                $scope.goods_select_click = function (sku) {
                    //若设置配置项设置的商品选择方式是商品级
                    if ($rootScope.configData.choseGoodsType == 1) {
                        //get_goods_by_code_local(sku.GoodsCode);
                    } else {
                        $scope.sku = sku;
                        window_id = ngDialog.open({closeByDocument: false,
                            template: './html/component/component_edit_num.html',
                            disableAnimation: true,
                            scope: $scope,
                            //                closeByDocument: false
                            trapFocus: false,
                        });
                    }
                };

            }]
        }
    })
;
